<template>
  <div class="maintenance-records-container">
    <div class="maintenance-records-header">
      <div class="header-actions">
        <el-button type="primary" plain size="small" @click="goBack">
          <el-icon><Back /></el-icon> 返回首页
        </el-button>
      </div>
      <h1>景点维修记录</h1>
      <p>查看青岛自然保护区景点维修记录</p>
    </div>

    <!-- 主要内容区域 -->
    <el-row :gutter="20">
      <!-- 左侧地图区域 -->
      <el-col :span="16">
        <el-card class="map-card">
          <div id="scenicMapView" class="map-container"></div>
        </el-card>
      </el-col>

      <!-- 右侧功能区域 -->
      <el-col :span="8">
        <!-- 景区选择 -->
        <el-card class="area-select-card">
          <template #header>
            <div class="card-header">
              <span>景点选择</span>
            </div>
          </template>

          <div class="area-tabs">
            <el-tabs v-model="activeArea" @tab-click="handleAreaChange">
              <el-tab-pane label="全部景点" name="all"></el-tab-pane>
              <el-tab-pane label="胶南灵山岛景点" name="erdihu"></el-tab-pane>
            <el-tab-pane label="大公岛景点" name="yunmen"></el-tab-pane>
            <el-tab-pane label="大泽山景点" name="bailang"></el-tab-pane>
            <el-tab-pane label="崂山景点" name="xiashan"></el-tab-pane>
            <el-tab-pane label="胶州艾山景点" name="binhai"></el-tab-pane>
            <el-tab-pane label="马山景点" name="mihe"></el-tab-pane>
            </el-tabs>
          </div>
        </el-card>

        <!-- 维修状态筛选 -->
        <el-card class="filter-card">
          <template #header>
            <div class="card-header">
              <span>维修状态筛选</span>
            </div>
          </template>

          <div class="filter-options">
            <el-radio-group v-model="selectedStatus" @change="handleStatusFilterChange">
              <el-radio-button label="all">全部</el-radio-button>
              <el-radio-button label="pending">待处理</el-radio-button>
              <el-radio-button label="in-progress">处理中</el-radio-button>
              <el-radio-button label="resolved">已解决</el-radio-button>
            </el-radio-group>
          </div>
        </el-card>

        <!-- 搜索框 -->
        <el-card class="search-card">
          <template #header>
            <div class="card-header">
              <span>搜索景点</span>
            </div>
          </template>

          <el-input
            v-model="searchQuery"
            placeholder="输入景点名称搜索"
            prefix-icon="Search"
            clearable
            @input="handleSearch"
          />
        </el-card>

        <!-- 统计信息 -->
        <el-card class="stats-card">
          <template #header>
            <div class="card-header">
              <span>维修统计</span>
            </div>
          </template>

          <div class="stats-content">
            <el-row :gutter="20">
              <el-col :span="8">
                <div class="stat-item">
                  <div class="stat-value">{{ pendingCount }}</div>
                  <div class="stat-label">待处理</div>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="stat-item">
                  <div class="stat-value">{{ inProgressCount }}</div>
                  <div class="stat-label">处理中</div>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="stat-item">
                  <div class="stat-value">{{ resolvedCount }}</div>
                  <div class="stat-label">已解决</div>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 维修记录列表 -->
    <el-card class="records-list-card">
      <template #header>
        <div class="card-header">
          <span>维修记录列表</span>
          <el-button type="primary" size="small" @click="refreshData">
            <el-icon><Refresh /></el-icon> 刷新数据
          </el-button>
        </div>
      </template>

      <div v-loading="loading">
        <el-table
          :data="maintenanceRecords"
          style="width: 100%"
          @row-click="handleRowClick"
          empty-text="暂无维修记录数据"
        >
          <el-table-column prop="scenicName" label="景点名称" min-width="120" />
          <el-table-column prop="title" label="问题标题" min-width="150" />
          <el-table-column prop="reportDateFormatted" label="上报时间" min-width="150" />
          <el-table-column label="严重程度" min-width="100">
            <template #default="scope">
              <el-tag :type="getSeverityTagType(scope.row.severity)">
                {{ getSeverityText(scope.row.severity) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="状态" min-width="100">
            <template #default="scope">
              <el-tag :type="getStatusTagType(scope.row.status)">
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" min-width="100" fixed="right">
            <template #default="scope">
              <el-button
                size="small"
                type="primary"
                @click.stop="viewRecordDetails(scope.row)"
              >
                查看详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
  </div>

  <!-- 详情抽屉 -->
  <el-drawer
    v-model="showDetailsDrawer"
    title="维修记录详情"
    direction="rtl"
    size="500px"
  >
    <div v-if="currentRecord" class="record-details">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="景点名称">
          {{ currentRecord.scenicName }}
        </el-descriptions-item>

        <el-descriptions-item label="问题标题">
          {{ currentRecord.title }}
        </el-descriptions-item>

        <el-descriptions-item label="问题描述">
          {{ currentRecord.description }}
        </el-descriptions-item>

        <el-descriptions-item label="严重程度">
          <el-tag :type="getSeverityTagType(currentRecord.severity)">
            {{ getSeverityText(currentRecord.severity) }}
          </el-tag>
        </el-descriptions-item>

        <el-descriptions-item label="上报者">
          {{ currentRecord.reporter }}
        </el-descriptions-item>

        <el-descriptions-item label="上报时间">
          {{ currentRecord.reportDateFormatted }}
        </el-descriptions-item>
        <el-descriptions-item label="处理意见">
          <template v-if="currentRecord.comments && currentRecord.comments.length > 0">
            <div v-for="(comment, index) in currentRecord.comments" :key="index" class="comment-text-simple">
              {{ comment.text }}
            </div>
          </template>
          <el-empty v-else description="暂无处理意见" :image-size="50"></el-empty>
        </el-descriptions-item>

        <el-descriptions-item label="当前状态">
          <el-tag :type="getStatusTagType(currentRecord.status)">
            {{ getStatusText(currentRecord.status) }}
          </el-tag>
        </el-descriptions-item>

        <el-descriptions-item label="问题图片" v-if="currentRecord.photoBase64">
          <el-image
            style="width: 100%; max-height: 300px"
            :src="currentRecord.photoBase64"
            fit="contain"
            :preview-src-list="[currentRecord.photoBase64]"
          ></el-image>
        </el-descriptions-item>
      </el-descriptions>



      <div class="details-actions">
        <el-button type="primary" @click="locateOnMap(currentRecord)">
          <el-icon><Location /></el-icon> 在地图上定位
        </el-button>
      </div>
    </div>
  </el-drawer>
</template>

<script setup lang="ts">
declare global {
  interface Window {
    _tempFeatures: __esri.Graphic[]
  }
}
import { ref, onMounted, computed } from 'vue'
import { Back, Search, Refresh, Location } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/userStore'
import { useRouter } from 'vue-router'
import Map from '@arcgis/core/Map'
import MapView from '@arcgis/core/views/MapView'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer'
import Graphic from '@arcgis/core/Graphic'
import SimpleMarkerSymbol from '@arcgis/core/symbols/SimpleMarkerSymbol'
import gaodeLayer from '@/utils/GaoDeBaseLayer'

// 维修记录接口
interface MaintenanceRecord {
  id: string
  title: string
  description: string
  severity: string
  photoBase64: string
  reportDate: string
  reportDateFormatted: string
  status: string
  reporter: string
  comments: { user: string; text: string; date: string }[]
  // 额外添加的字段，用于显示
  scenicName: string
  OBJECTID: number
  featureIndex: number
  geometryInfo?: {
    x: number | null
    y: number | null
    type: string
  }
}

// 用户存储和路由
const userStore = useUserStore()
const router = useRouter()

// 地图和图层
let view: __esri.MapView
let featureLayers: __esri.FeatureLayer[] = []

// 状态变量
const loading = ref(true)
const searchQuery = ref('')
const allFeatures = ref<any[]>([])
const selectedStatus = ref('all')
const showDetailsDrawer = ref(false)
const currentRecord = ref<MaintenanceRecord | null>(null)

// 当前选中的景区
const activeArea = ref('all') // 默认全部景区

// 各个景区的中心坐标
const areaCenters = {
  all: [120.3, 36.2], // 全部景区的中心点，调整为新坐标区域的中心
  erdihu: [120.179558,35.765965], // 胶南灵山岛坐标
  yunmen: [120.503415,35.967122], // 大公岛坐标
  bailang: [120.022251,37.00615], // 大泽山坐标
  xiashan: [120.605305,36.198964], // 崂山坐标
  binhai: [119.93718,36.121442], // 胶州艾山坐标
  mihe: [120.651138,36.340289] // 马山坐标
}

// 计算属性：维修记录列表
const maintenanceRecords = computed(() => {
  // 从所有要素中提取维修记录
  const records: MaintenanceRecord[] = []

  allFeatures.value.forEach((feature, featureIndex) => {
    if (feature.attributes.MaintanceDataJson) {
      try {
        const maintanceData = JSON.parse(feature.attributes.MaintanceDataJson)
        if (Array.isArray(maintanceData) && maintanceData.length > 0) {
          maintanceData.forEach((record: any) => {
            // 根据状态筛选
            if (selectedStatus.value === 'all' || record.status === selectedStatus.value) {
              // 根据景区筛选
              const shouldInclude = activeArea.value === 'all' ||
                (activeArea.value === 'erdihu' && feature.attributes.OwnerScenic === '胶南灵山岛保护区') ||
        (activeArea.value === 'yunmen' && feature.attributes.OwnerScenic === '大公岛保护区') ||
        (activeArea.value === 'bailang' && feature.attributes.OwnerScenic === '大泽山保护区');

              // 根据搜索条件筛选
              if (shouldInclude && (!searchQuery.value || feature.attributes.ScenicName.includes(searchQuery.value))) {
                records.push({
                  ...record,
                  scenicName: feature.attributes.ScenicName,
                  OBJECTID: feature.attributes.OBJECTID,
                  featureIndex,
                  reportDateFormatted: formatDate(record.reportDate),
                  geometryInfo: feature.geometryInfo
                })
              }
            }
          })
        }
      } catch (e) {
        console.error('解析维修数据失败', e)
      }
    }
  })

  // 按上报时间排序，最新的在前面
  return records.sort((a, b) => new Date(b.reportDate).getTime() - new Date(a.reportDate).getTime())
})

// 计算属性：待处理数量
const pendingCount = computed(() => {
  return countRecordsByStatus('pending')
})

// 计算属性：处理中数量
const inProgressCount = computed(() => {
  return countRecordsByStatus('in-progress')
})

// 计算属性：已解决数量
const resolvedCount = computed(() => {
  return countRecordsByStatus('resolved')
})

// 统计指定状态的记录数量
const countRecordsByStatus = (status: string) => {
  let count = 0

  allFeatures.value.forEach(feature => {
    if (feature.attributes.MaintanceDataJson) {
      try {
        const maintanceData = JSON.parse(feature.attributes.MaintanceDataJson)
        if (Array.isArray(maintanceData)) {
          // 根据景区筛选
          const shouldInclude = activeArea.value === 'all' ||
            (activeArea.value === 'erdihu' && feature.attributes.OwnerScenic === '胶南灵山岛保护区') ||
        (activeArea.value === 'yunmen' && feature.attributes.OwnerScenic === '大公岛保护区') ||
        (activeArea.value === 'bailang' && feature.attributes.OwnerScenic === '大泽山保护区') ||
        (activeArea.value === 'xiashan' && feature.attributes.OwnerScenic === '崂山保护区') ||
        (activeArea.value === 'binhai' && feature.attributes.OwnerScenic === '胶州艾山保护区') ||
        (activeArea.value === 'mihe' && feature.attributes.OwnerScenic === '马山保护区');

          if (shouldInclude) {
            // 根据搜索条件筛选
            if (!searchQuery.value || feature.attributes.ScenicName.includes(searchQuery.value)) {
              count += maintanceData.filter((record: any) => record.status === status).length
            }
          }
        }
      } catch (e) {
        console.error('解析维修数据失败', e)
      }
    }
  })

  return count
}

// 查询保护区数据
const queryFeatures = async () => {
  if (!featureLayers || featureLayers.length === 0) return

  loading.value = true
  try {
    const allQueryResults: any[] = []
    const allOriginalFeatures: __esri.Graphic[] = []

    // 查询景点图层
    const layer = featureLayers[0]
    const query = layer.createQuery()
    query.where = '1=1' // 查询所有数据
    query.outFields = ['*']

    try {
      const result = await layer.queryFeatures(query)

      // 为每个要素添加索引信息
      const processedFeatures = result.features.map((feature, featureIndex) => {
        // 存储原始要素
        allOriginalFeatures.push(feature)

        return {
          _index: featureIndex,
          _layerIndex: 0,
          _layerType: 'scenic',
          attributes: { ...feature.attributes },
          geometryInfo: feature.geometry
            ? {
                x: feature.geometry.type === 'point' ? (feature.geometry as __esri.Point).x : null,
                y: feature.geometry.type === 'point' ? (feature.geometry as __esri.Point).y : null,
                type: feature.geometry.type,
              }
            : null,
        }
      })

      allQueryResults.push(...processedFeatures)
    } catch (layerError) {
      console.error('查询景点图层失败:', layerError)
    }

    // 存储原始的ESRI要素对象到非响应式变量中
    window._tempFeatures = allOriginalFeatures

    // 将要素数据存储到响应式变量中
    allFeatures.value = allQueryResults
  } catch (error) {
    console.error('查询景点数据失败', error)
    allFeatures.value = []
  } finally {
    loading.value = false
  }
}

// 初始化地图
const initMap = async () => {
  // 创建地图实例
  const map = new Map({
    basemap: 'streets-vector',
  })

  // 创建地图视图
  view = new MapView({
    container: 'scenicMapView',
    map: map,
    center: areaCenters[activeArea.value as keyof typeof areaCenters], // 根据当前选中的景区设置中心点
    zoom: 10,
    popup: {
      dockEnabled: true,
      dockOptions: {
        buttonEnabled: false,
        breakpoint: false,
      },
    },
  })

  // 创建景点要素图层
  const featureLayer = new FeatureLayer({
    url: 'https://services8.arcgis.com/hvBaJk0FLVU4yP47/arcgis/rest/services/ScenicPointLayer/FeatureServer/0',
    outFields: ['*'],
    popupEnabled: false,
    renderer: {
      type: 'unique-value',
      field: 'ScenicType',
      uniqueValueInfos: [
        {
          value: '自然景观',
          symbol: {
            type: 'simple-marker',
            color: [34, 139, 34],
            size: 8,
            outline: {
              color: 'white',
              width: 1
            }
          }
        },
        {
          value: '人文景观',
          symbol: {
            type: 'simple-marker',
            color: [30, 144, 255],
            size: 8,
            outline: {
              color: 'white',
              width: 1
            }
          }
        },
        {
          value: '历史遗迹',
          symbol: {
            type: 'simple-marker',
            color: [255, 140, 0],
            size: 8,
            outline: {
              color: 'white',
              width: 1
            }
          }
        },
        {
          value: '休闲娱乐',
          symbol: {
            type: 'simple-marker',
            color: [255, 20, 147],
            size: 8,
            outline: {
              color: 'white',
              width: 1
            }
          }
        },
        {
          value: '观景台',
          symbol: {
            type: 'simple-marker',
            color: [128, 128, 128],
            size: 8,
            outline: {
              color: 'white',
              width: 1
            }
          }
        }
      ]
    },
    labelingInfo: [
      {
        labelExpression: '$feature.ScenicName',
        symbol: {
          type: 'text',
          color: 'black',
          font: {
            size: 10,
            weight: 'bold'
          }
        },
        minScale: 50000
      }
    ]
  })

  // 将图层添加到地图
  map.add(featureLayer)

  // 将图层存储到数组中用于查询
  featureLayers = [featureLayer]

  // 加载要素数据
  await queryFeatures()
}

// 处理景区切换
const handleAreaChange = () => {
  // 将地图中心移动到选中的景区
  view?.goTo({
    center: areaCenters[activeArea.value as keyof typeof areaCenters],
    zoom: activeArea.value === 'all' ? 10 : 13,
  })
}

// 处理状态筛选变化
const handleStatusFilterChange = () => {
  // 状态筛选变化时不需要重新查询数据，只需要重新计算 maintenanceRecords
}

// 处理搜索
const handleSearch = () => {
  // 搜索条件变化时不需要重新查询数据，只需要重新计算 maintenanceRecords
}

// 刷新数据
const refreshData = async () => {
  await queryFeatures()
  ElMessage.success('数据已刷新')
}

// 处理表格行点击
const handleRowClick = (row: MaintenanceRecord) => {
  viewRecordDetails(row)
}

// 查看记录详情
const viewRecordDetails = (record: MaintenanceRecord) => {
  currentRecord.value = record
  showDetailsDrawer.value = true
}

// 在地图上定位
const locateOnMap = (record: MaintenanceRecord) => {
  // 从非响应式存储中获取原始要素
  const originalFeature = window._tempFeatures?.[record.featureIndex]
  if (originalFeature) {
    highlightFeatureOnMap(originalFeature)
  }
}

// 在地图上高亮显示要素
const highlightFeatureOnMap = (feature: any) => {
  if (!feature || !feature.geometry) return

  // 清除之前的高亮
  view?.graphics.removeAll()

  // 创建高亮符号
  const highlightSymbol = new SimpleMarkerSymbol({
    color: [255, 255, 255, 0.8],
    size: 16,
    outline: {
      color: [0, 122, 194],
      width: 3,
    },
  })

  // 创建高亮图形
  const highlightGraphic = new Graphic({
    geometry: feature.geometry,
    symbol: highlightSymbol,
  })

  // 添加到地图
  view?.graphics.add(highlightGraphic)

  // 将视图中心移动到要素位置
  view?.goTo({
    target: feature.geometry,
    zoom: 15,
  })
}

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  switch (status) {
    case 'pending':
      return 'warning'
    case 'in-progress':
      return 'primary'
    case 'resolved':
      return 'success'
    default:
      return 'info'
  }
}

// 获取状态文本
const getStatusText = (status: string) => {
  switch (status) {
    case 'pending':
      return '待处理'
    case 'in-progress':
      return '处理中'
    case 'resolved':
      return '已解决'
    default:
      return '未知'
  }
}

// 获取严重程度标签类型
const getSeverityTagType = (severity: string) => {
  switch (severity) {
    case 'minor':
      return 'info'
    case 'moderate':
      return 'warning'
    case 'critical':
      return 'danger'
    default:
      return 'info'
  }
}

// 获取严重程度文本
const getSeverityText = (severity: string) => {
  switch (severity) {
    case 'minor':
      return '轻微'
    case 'moderate':
      return '中等'
    case 'critical':
      return '严重'
    default:
      return '未知'
  }
}



// 格式化日期
const formatDate = (dateString: string) => {
  try {
    const date = new Date(dateString)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  } catch (e) {
    return dateString
  }
}

// 返回首页
const goBack = () => {
  router.push('/')
}

// 页面加载完成后初始化地图
onMounted(() => {
  initMap()
})
</script>

<style scoped lang="scss">
.maintenance-records-container {
  padding: 20px;
}

.maintenance-records-header {
  margin-bottom: 20px;
  background-color: #fff;
  padding: 15px 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  border-left: 4px solid #67c23a;
}

.header-actions {
  margin-bottom: 15px;
}

.maintenance-records-header h1 {
  font-size: 24px;
  color: #303133;
  margin-bottom: 8px;
}

.maintenance-records-header p {
  color: #606266;
  font-size: 14px;
}

.map-container {
  height: 300px;
  width: 100%;
  position: relative;
}

.map-card,
.area-select-card,
.filter-card,
.search-card,
.stats-card,
.records-list-card {
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  border-radius: 4px;
  overflow: hidden;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-options {
  padding: 10px 0;
}

.stats-content {
  padding: 10px 0;
}

.stat-item {
  text-align: center;
  padding: 10px;
  border-radius: 4px;
  background-color: #f5f7fa;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
}

.stat-label {
  font-size: 14px;
  color: #606266;
  margin-top: 5px;
}

.record-details {
  padding: 20px;
}

.comments-section {
  margin-top: 20px;
  border-top: 1px solid #ebeef5;
  padding-top: 15px;
}

.comments-section h3 {
  margin-bottom: 15px;
  color: #303133;
  font-size: 16px;
}

.comment-content {
  background-color: #f8f8f8;
  padding: 10px;
  border-radius: 4px;
}

.comment-content h4 {
  margin: 0 0 5px 0;
  font-size: 14px;
  color: #303133;
}

.comment-content p {
  margin: 0;
  color: #606266;
}

.comment-item-inline {
  margin-bottom: 10px;
  padding: 8px;
  background-color: #f8f8f8;
  border-radius: 4px;
  border-left: 3px solid #409eff;
}

.comment-header-inline {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
  font-size: 12px;
  color: #606266;
}

.comment-text-inline {
  color: #303133;
}

.comment-text-simple {
  padding: 8px;
  margin-bottom: 8px;
  background-color: #f8f8f8;
  border-radius: 4px;
  color: #303133;
  border-left: 3px solid #409eff;
}

.details-actions {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .maintenance-records-container {
    padding: 10px;
  }

  .map-container {
    height: 250px;
  }

  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
}
</style>
